package com.defangit.award.orm;

import com.defangit.award.domain.Award;
import com.defangit.award.domain.Prize;
import com.defangit.award.domain.WinningInfo;
import com.defangit.award.domain.WinningStatus;
import com.defangit.award.extend.point.AwardListener;
import com.laogen.plugins.PluginManager;
import laogen.hibernate.CommonFinder;
import laogen.hibernate.CommonService;
import laogen.lang.exception.ParameterNotValidException;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

/**
 * Created by zhangfagen on 2019/1/1.
 */
public class AwardService extends CommonService<Award>{
    private static Logger logger= LoggerFactory.getLogger(AwardService.class);
    private static List<AwardListener> listeners=PluginManager.getInstance().getListeners(AwardListener.class);

    /**
     * 添加抽奖信息
     * @param award 抽奖信息
     * @return 添加后的抽奖信息
     */
    public Award addAward(Award award){
        if(award==null) throw ParameterNotValidException.nullParameter("要添加的抽奖活动");
        add(award);
        commitSession();
        return award;
    }

    public boolean delAward(int id){
        Award award=get(id)
                .orElseThrow(()->ParameterNotValidException.zeroIdOrEntityNonExist("要删除的抽奖活动id"));
        delete(award);
        commitSession();
        return true;
    }

    public AwardFinder findAll(){
        return new AwardFinder();
    }

    public class AwardFinder extends CommonFinder<Award> {
        private DetachedCriteria dc=detachedAll();
        @Override
        public Criteria getCriteria() {
            return dc.getExecutableCriteria(getSession());
        }

        @Override
        public DetachedCriteria getDetachedCriteria() {
            return dc;
        }

        public AwardFinder prize(Integer prize){

            if(prize!=null && prize!=0)
                dc=dc.createAlias("prizes","prize")
                    .add(Restrictions.eq("prize.id",prize));
            return this;
        }
    }

}
